package com.qf.service.impl;

import com.qf.config.RedisKey;
import com.qf.dao.mapper.QfCourseDao;
import com.qf.dao.mapper.QfOrderDao;
import com.qf.dao.repository.QfOrderDetailRepisotry;
import com.qf.dao.repository.QfOrderRepository;
import com.qf.pojo.dto.LiveUser;
import com.qf.pojo.dto.QfOrder;
import com.qf.pojo.dto.QfOrderDetail;
import com.qf.pojo.reqVo.OrderReq;
import com.qf.pojo.resVo.BaseResult;
import com.qf.pojo.resVo.OrderResp;
import com.qf.service.OrderService;
import com.qf.service.UserService;
import com.qf.utils.GenerateOrderNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    QfCourseDao qfCourseDao;
    @Autowired
    UserService userService;
    @Autowired
    QfOrderRepository qfOrderRepository;
    @Autowired
    QfOrderDetailRepisotry qfOrderDetailRepisotry;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    QfOrderDao qfOrderDao;
    /**
     * 订单的添加
     * 保证接口的安全性
     * @param orderReq
     * @return
     */
    @Override
    //控制事务，要不一起成功，要不一起失败
    @Transactional
    public BaseResult addOrder(OrderReq orderReq, HttpServletRequest request) {

        if (orderReq.getIds()==null||orderReq.getIds().size()<=0){
            return new BaseResult(0,"没有接算的课程信息！",null,null);
        }
        if (orderReq.getMoney()==null||orderReq.getMoney()<=0.0){
            return new BaseResult(0,"总价有错误！",null,null);
        }

        //获取到登录用户
        BaseResult userByToken = userService.findUserByToken(request);
        if (userByToken.getCode()==0){
            return userByToken;
        }
        LiveUser liveUser =(LiveUser) userByToken.getData();
        //验证我们前端的价格是否是与数据库中的价格一致
        //1.使用前端传入的课程id集合，进行查询，查询出每个课程的详细内容/直接使用sql计算出课程的总价

       Double sumMoney =  qfCourseDao.sumMoeny(orderReq.getIds());
        //2.使用前端的价格与数据库计算的价格进行比对
        if (!sumMoney.toString().equals(orderReq.getMoney().toString())){
            return new BaseResult(0,"生成订单失败!价格不符",null,null);
        }
        //3.添加总订单
            //1.生成总订单的id
        GenerateOrderNum generateOrderNum = new GenerateOrderNum();
        String orderId= generateOrderNum.generate("");
            //2.组装总订单的信息
        QfOrder qfOrder = new QfOrder();
        qfOrder.setOrderid(orderId);
        //支付状态设置为 1
        qfOrder.setOrderStatus(1);
        qfOrder.setCreatetime(new Date());
        qfOrder.setOrderPay(sumMoney);
        qfOrder.setUserid(liveUser.getUserId());
        //总订单信息组装完成后，就可以进行添加
        QfOrder save = qfOrderRepository.save(qfOrder);
        //总订单项已经生成，我们需要根据课程id的不同，生成子订单项
        List<Integer> ids = orderReq.getIds();
        //循环课程id 生成订单子项
        for (Integer id:ids
             ) {

            QfOrderDetail qfOrderDetail = new QfOrderDetail();
            //订单子项ID
            qfOrderDetail.setOrderDetailId(generateOrderNum.generate(""));
            //总订单ID
            qfOrderDetail.setOrderId(orderId);
            //设置课程信息
            qfOrderDetail.setCourseId(id);
            qfOrderDetail.setCreatetime(new Date());
            //循环添加订单子项信息
            qfOrderDetailRepisotry.save(qfOrderDetail);
            //如果订单生成成功！则清除掉购物车中的该商品的信息
            redisTemplate.opsForHash().delete(RedisKey.SHOP_CARD+liveUser.getUserId().toString(),id.toString());
            //判断该购物车是否为null
            Long size = redisTemplate.opsForHash().size(RedisKey.SHOP_CARD + liveUser.getUserId().toString());
            if (size==0){
                //将购物车进行删除处理
                redisTemplate.delete(RedisKey.SHOP_CARD + liveUser.getUserId().toString());
            }
        }


        return new BaseResult(1,"生成订单成功！",null,null);
    }

    @Override
    public BaseResult findOrderByUserId(HttpServletRequest request) {
        //1.解析request请求获取到用户信息
        //获取到登录用户
        BaseResult userByToken = userService.findUserByToken(request);
        if (userByToken.getCode()==0){
            return userByToken;
        }
        LiveUser liveUser =(LiveUser) userByToken.getData();
        //去数据库进行三表联查 订单总表，订单的详情表，课程表
        List<OrderResp> orderResps = qfOrderDao.findOrderByUserId(liveUser.getUserId(),1);
        return new BaseResult(1,"查询成功！",orderResps,null);
    }

    @Override
    public BaseResult cancelPay(Map map) {
        //直接修改该订单的状态。将为1的状态改为4
        Optional<QfOrder> orderid = qfOrderRepository.findById(map.get("orderid").toString());
        if (orderid.isPresent()){
            QfOrder qfOrder = orderid.get();
            //将状态进行改变
            qfOrder.setOrderStatus(4);
            //执行修改
            qfOrderRepository.saveAndFlush(qfOrder);

            return new BaseResult(1,"取消支付成功！",null,null);
        }
        return new BaseResult(0,"取消失败！",null,null);
    }

    @Override
    public BaseResult findOldOrdersByUserid(HttpServletRequest request) {
        //1.解析request请求获取到用户信息
        //获取到登录用户
        BaseResult userByToken = userService.findUserByToken(request);
        if (userByToken.getCode()==0){
            return userByToken;
        }
        LiveUser liveUser =(LiveUser) userByToken.getData();
        //去数据库进行三表联查 订单总表，订单的详情表，课程表
        List<OrderResp> orderResps = qfOrderDao.findOrderByUserId(liveUser.getUserId(),null);
        return new BaseResult(1,"查询成功！",orderResps,null);
    }
}
